var hlx_guid;
var hlx_cookiePrefix = 'hlx';
var hlx_historyId = '#hlx_history';
var hlx_history_click_funName = 'hlx_history_click';
jQuery(document).ready(function ($) {
    checkIsRunState(hlx_cookiePrefix, function (guid) {
        hlx_guid = guid;
        var runBtn = $('#fairRun');
        runBtn.text('运行中...');
        runBtn.attr('disabled', 'disabled');
        $(hlx_historyId).hide();
        hlx_polling();
    });

    initHistoryDropDownMenu(hlx_cookiePrefix, hlx_historyId, hlx_history_click_funName);
    //addItemToHistory(hlx_cookiePrefix, hlx_historyId, 'wu_1cc362oecumhfj1i3618jfbak0', new Date(), hlx_history_click_funName);

    //点击运行 检测HLXFX算法是否完成
    $("#fairRun").click(function (event) {
        hlx_guid = WebUploader.Base.guid();
        $.ajax({
            url: 'algorithm/HLXFX.do',
            type: 'POST',
            dataType: 'json',
            async: true,
            beforeSend: function () {
                setRunButtonDisable(true);
                $('#fair_ys_select').html('<option selected="true" disabled="true" value="0">请选择</option>');
                $('#fair_table_div').empty();
            },
            data: {
                guid: hlx_guid
            },
            success: function (path) {
                //如果status=0 则请求成功
                if (!path.status) {
                    //请求成功后轮询算法是否完成
                    hlx_polling();
                } else {
                    alert(path.msg);
                    setRunButtonDisable(false);
                }
            },
            error: function () {
                alert("网络繁忙，请稍后再试！");
                setRunButtonDisable(false);
            }
        })
    });

    function setRunButtonDisable(disable) {
        var runBtn = $('#fairRun');
        if (disable) {
            runBtn.text('运行中...');
            runBtn.attr('disabled', 'disabled');
            $(hlx_historyId).hide();
            setRunState(hlx_cookiePrefix, true, hlx_guid);
        } else {
            runBtn.text('运行');
            runBtn.removeAttr('disabled');
            $(hlx_historyId).show();
            setRunState(hlx_cookiePrefix, false);
        }
    }

    //轮询检测HLXFX算法是否完成
    function hlx_polling() {
        $.ajax({
            url: 'data/checkHLXFX.do',
            type: 'POST',
            async: true,
            dataType: 'json',
            data: {
                guid: hlx_guid
            },
            success: function (result) {
                //成功
                if (!result.status) //因为后台数据status为1 所以暂时把!result.status的！ 去掉了！
                {
                    //alert(result.data);
                    hlx_getFairCause(); //成功后就获取YS1的值
                    setRunButtonDisable(false);
                    addItemToHistory(hlx_cookiePrefix, hlx_historyId, hlx_guid, new Date(), hlx_history_click_funName);
                } else if (result.msg != 'no') {
                    alert('服务器报错：' + result.msg);
                    setRunButtonDisable(false);
                }
                //不成功 轮询
                else {
                    window.setTimeout(function () {
                        hlx_polling()
                    }, 30000);
                }
            },
            error: (function () {
                alert("轮询出错");
                setRunButtonDisable(false);
            })
        })
    }

    $("#fair_ys_select").change(function (event) {
        var ysname = $("#fair_ys_select option:selected").val();
        if (ysname == '0')
            return;
        getFairTableData(ysname);
    })

    function getFairTableData(ysName) {
        $.ajax({
            url: 'data/getHlxfxTable.do',
            type: 'POST',
            async: true,
            dataType: 'json',
            data: {
                YS_name: ysName,
                guid: hlx_guid
            },
            success: function (result) {
                if (!result.status) {
                    setFairTable(result);
                } else {
                    alert(result.msg);
                }
            },
            error: function () {
                alert("表格数据请求失败!");
            }
        })
    }

    function setFairTable(result) {
        var i, j;
        $('#fair_table_div').empty(); //清空所有子节点
        var html = "";
        html += '<table id="fairTable" class="table table-bordered table-hover cause-table run">';
        html += '</table>';
        $('#fair_table_div').html(html);
        var fTable = document.getElementById("fairTable");
        for (i in result.data) {
            var tr = fTable.insertRow(i);
            for (j in result.data[i]) {
                var td = tr.insertCell(j);
                td.innerHTML = result.data[i][j];
            }
        }
        j++;
        var persent = 100 / j;
        var tableWidth = persent.toString();
        tableWidth += "%";
        $(".cause-table td").css({
            width: tableWidth,
            minwidth: '10%'
        });
    }

});

function hlx_getFairCause() {
    $.ajax({
        url: 'data/getHlxfxYS.do',
        type: 'POST',
        async: true,
        dataType: 'json',
        data: {
            guid: hlx_guid
        },
        success: function (result) {
            console.log(result);
            //result因素一的数组 成功后插入元素
            if (!result.status) {
                hlx_addOption(result, "#fair_ys_select");
            } else {
                $('#fair_ys_select').html('<option selected="true" disabled="true" value="0">请选择</option>');
                alert(result.msg);
            }
        },
        error: function () {
            alert("因素获取失败");
        }
    })
}

function hlx_addOption(result, id) {
    var sel = $(id);
    sel.html('');
    for (var index in result.data) {
        var opt = document.createElement('option');
        opt.value = index;
        opt.innerHTML = result.data[index];
        sel.append(opt);
    }
    sel.trigger('change');
}

function hlx_history_click(sender){
    hlx_guid = $(sender).attr('value');
    hlx_getFairCause();
}